import json

from django.forms import forms
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from django.views.decorators.csrf import csrf_exempt
from django.forms.widgets import TextInput
from wepapi.models import Task
from wepapi.utils.Pagination import Pagination
from wepapi.utils.bootstrap import BootStrapModelForm


class taskModelFormlist(BootStrapModelForm):
    class Meta:
        model = Task
        fields = '__all__'
        widgets = {
            'detail': TextInput
        }


@csrf_exempt
def task_list(request):
    tasks = Task.objects.all()
    page_object = Pagination(request, tasks)
    page_string = page_object.html()

    if request.method == 'GET':
        uform = taskModelFormlist()
        return render(request, 'task_list.html',
                      {"uform": uform, "queryset": page_object.page_queryset, 'page_string': page_string})

    if request.method == 'POST':
        tasks_list = [task.to_dict() for task in tasks]
        data_dict = {'status': True, 'data': tasks_list, 'code': 200}
        return HttpResponse(json.dumps(data_dict), content_type="application/json")


@csrf_exempt
def task_ajax(request):
    # if request.method == "GET":
    #     print(request.GET)
    #     return HttpResponse('GET')
    #
    # if request.method == "POST":
    #   print(request.POST)
    #   return HttpResponse('POST')
    print(request.POST)
    print(request.GET)

    data_dict = {'status': True, 'data': [11, 22, 33, 44], 'code': 200}
    json_string = json.dumps(data_dict)
    return HttpResponse(json_string)


@csrf_exempt
def task_add(request):
    # Task.objects.filter()
    # {'level': ['3'], 'title': ['请问请问'], 'create_time': ['2024-12-11'], 'detail': ['请问请问'], 'user': ['1']}
    print(request.POST)
    # 用户发送过来的数据进行校验
    form = taskModelFormlist(request.POST)
    if form.is_valid():
        Task.objects.filter()
        form.save()
        data_dict = {'status': True, 'code': 200}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {'status': False, 'error': form.errors, 'code': 201}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
